"""
认证API路由
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from loguru import logger

from app.core.deps import get_db, get_current_user
from app.models.user import User, UserRole, UserStatus
from app.schemas.auth import (
    UserLogin,
    UserRegister,
    TokenResponse,
    UserResponse
)
from app.utils.security import (
    hash_password,
    verify_password,
    create_access_token
)


router = APIRouter()


@router.post("/register", response_model=UserResponse)
async def register(
    user_data: UserRegister,
    db: AsyncSession = Depends(get_db)
):
    """
    用户注册
    """
    try:
        logger.info(f"用户注册请求: {user_data.username}")
        
        # 检查用户名是否已存在
        stmt = select(User).where(User.username == user_data.username)
        result = await db.execute(stmt)
        existing_user = result.scalar_one_or_none()
        
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="用户名已存在"
            )
        
        # 检查邮箱是否已存在
        if user_data.email:
            stmt = select(User).where(User.email == user_data.email)
            result = await db.execute(stmt)
            existing_email = result.scalar_one_or_none()
            
            if existing_email:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已被使用"
                )
        
        # 创建新用户
        new_user = User(
            username=user_data.username,
            email=user_data.email,
            phone=user_data.phone,
            hashed_password=hash_password(user_data.password),
            role=UserRole.CUSTOMER,
            status=UserStatus.ACTIVE
        )
        
        db.add(new_user)
        await db.commit()
        await db.refresh(new_user)
        
        logger.info(f"用户注册成功: {new_user.username} (ID: {new_user.id})")
        
        return UserResponse(
            success=True,
            message="注册成功",
            user={
                "id": new_user.id,
                "username": new_user.username,
                "email": new_user.email,
                "role": new_user.role.value,
                "status": new_user.status.value
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"用户注册失败: {e}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"注册失败: {str(e)}"
        )


@router.post("/login", response_model=TokenResponse)
async def login(
    credentials: UserLogin,
    db: AsyncSession = Depends(get_db)
):
    """
    用户登录
    """
    try:
        logger.info(f"用户登录请求: {credentials.username}")
        
        # 查找用户
        stmt = select(User).where(User.username == credentials.username)
        result = await db.execute(stmt)
        user = result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )
        
        # 验证密码
        if not verify_password(credentials.password, user.hashed_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )
        
        # 检查用户状态
        if user.status != UserStatus.ACTIVE:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"账户状态异常: {user.status.value}"
            )
        
        # 生成访问令牌
        token_data = {
            "sub": str(user.id),  # JWT规范要求sub必须是字符串
            "username": user.username,
            "role": user.role.value
        }
        access_token = create_access_token(token_data)
        
        # 更新登录信息（可选）
        # user.login_count = str(int(user.login_count or "0") + 1)
        # user.last_login_at = datetime.now().isoformat()
        # await db.commit()
        
        logger.info(f"用户登录成功: {user.username} (ID: {user.id})")
        
        return TokenResponse(
            success=True,
            access_token=access_token,
            token_type="bearer",
            user={
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "role": user.role.value,
                "is_vip": user.is_vip
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"用户登录失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"登录失败: {str(e)}"
        )


@router.get("/verify")
async def verify_token(
    current_user: User = Depends(get_current_user)
):
    """
    验证Token是否有效
    
    用于前端路由守卫验证token有效性
    """
    return {
        "success": True,
        "user": {
            "id": current_user.id,
            "username": current_user.username,
            "email": current_user.email,
            "role": current_user.role.value,
            "is_vip": current_user.is_vip
        }
    }

